# @Time : 2024-11-05 13:06
# @Author : Fioman 
# @Phone : 13149920693
"""
通过使用Queue可以进行多线程通信,并且是线程安全的,为什么是线程安全的呢?因为Queue内部就使用了
内部锁的机制来保证了线程安全.
get() 阻塞
put() 阻塞
empty() 是否为空
qsize() 队列大小
"""
import threading
import time
from queue import Queue


def get_detail_html(q: Queue):
    while True:
        try:
            url = q.get(block=False)
        except Exception as e:
            print(str(e))
            url = None
        print(f"queue.get() 是阻塞的,queue的长度为: {q.qsize()},获取到的url:{url}")
        print("get detail html started")
        time.sleep(2)
        print("get detail html finished")


def get_detail_url(q):
    while True:
        print("get detail url started")
        time.sleep(4)
        for i in range(20):
            q.put("http://projectsedu.com/{id}".format(id=i))
        print("get detail url end")


if __name__ == '__main__':
    q = Queue()
    threadDetailUrl = threading.Thread(target=get_detail_url, args=(q,))
    threadDetailUrl.start()
    for i in range(10):
        htmlThread = threading.Thread(target=get_detail_html, args=(q,))
        htmlThread.start()

    startTime = time.time()
    q.join()
    print("lastTime: {}".format(time.time() - startTime))
